package com.panshi.qiniuyun;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;

@Service
public class UploadImageImp extends UploadImageService {

    //七牛云文件上传管理器
    private UploadManager uploadManager;

    private String token;

    //private QiniuConfig config = new QiniuConfig();

    //七牛云认证管理
    public UploadImageImp(QiniuConfig config){
        this.config = config;
        init();
    }

    private void init(){
        //构建一个带指定Zone对象的配置类，注意这里的ZoneZone.zone2 需要根据主机选择
        uploadManager = new UploadManager(new Configuration(Zone.zone2()));
        Auth auth = Auth.create(config.getQiniuAccessKey(),config.getQiniuSecretKey());

        //根据命名空间生成的上传token
        token  = auth.uploadToken(config.getQiniuBucketName());
    }

    @Override
    public String uploadQNImg(FileInputStream file, String key) {
        try{
            //上传图片文件
            Response response = uploadManager.put(file,key,token,null,null);
            if(!response.isOK()){
                throw new RuntimeException("上传七牛云出错："+response.toString());
            }

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);

            //图片的外链地址，通过这个地址可以直接打开图片
            String path = config.getQiniuDomain()+"/"+putRet.key;

            return path;

        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return "";
    }

}
